package com.core136.service.partymember;

import com.core136.bean.account.Account;
import com.core136.bean.partymember.PartyMember;
import com.core136.bean.sys.PageParam;
import com.core136.common.enums.MessageCode;
import com.core136.common.retdataunit.RetDataBean;
import com.core136.common.retdataunit.RetDataTools;
import com.core136.common.utils.SysTools;
import com.core136.mapper.partymember.PartyMemberMapper;
import com.core136.service.account.AccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class PartyMemberService {
    private PartyMemberMapper partyMemberMapper;

    @Autowired
    public void setPartyMemberMapper(PartyMemberMapper partyMemberMapper) {
        this.partyMemberMapper = partyMemberMapper;
    }

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public int insertPartyMember(PartyMember partyMember) {
        return partyMemberMapper.insert(partyMember);
    }

    public int deletePartyMember(PartyMember partyMember) {
        return partyMemberMapper.delete(partyMember);
    }

    public int updatePartyMember(Example example, PartyMember partyMember) {
        return partyMemberMapper.updateByExampleSelective(partyMember, example);
    }

    public PartyMember selectOnePartyMember(PartyMember partyMember) {
        return partyMemberMapper.selectOne(partyMember);
    }

    public List<PartyMember> getPartyMemeberList(PartyMember partyMember) {
        return partyMemberMapper.select(partyMember);
    }

    /**
     * @param orgId
     * @param memberId
     * @return Map<String, String>
     * @Title: getMyMemberInfoByMemberId
     * @Description:  获取个人党员信息
     */
    public Map<String, String> getMyMemberInfoByMemberId(String orgId, String memberId) {
        return partyMemberMapper.getMyMemberInfoByMemberId(orgId, memberId);
    }

    /**
     * @param orgId
     * @param redcordList
     * @return int
     * @Title: deletePartyMenbers
     * @Description:  批量删除党员信息
     */
    public int deletePartyMenbers(String orgId, List<String> redcordList) {
        Example example = new Example(PartyMember.class);
        example.createCriteria().andEqualTo("orgId", orgId).andIn("recordId", redcordList);
        return partyMemberMapper.deleteByExample(example);
    }


    /**
     * @param orgId
     * @param partyOrgId
     * @param search
     * @return List<Map < String, String>>
     * @Title: getPartyMemberListByPartyOrgId
     * @Description:  按所属党组织获取党员列表
     */
    public List<Map<String, String>> getPartyMemberListByPartyOrgId(String orgId, String partyOrgId, String search) {
        return partyMemberMapper.getPartyMemberListByPartyOrgId(orgId, partyOrgId, "%" + search + "%");
    }

    /**
     * @param orgId
     * @param partyOrgId
     * @param search
     * @return List<Map < String, String>>
     * @Title: getPartyMemberAccountListByPartyOrgId
     * @Description:  获取账号绑定党员列表
     */
    public List<Map<String, String>> getPartyMemberAccountListByPartyOrgId(String orgId, String partyOrgId, String search) {
        return partyMemberMapper.getPartyMemberAccountListByPartyOrgId(orgId, partyOrgId, "%" + search + "%");
    }

    /**
     * @param pageParam
     * @param partyOrgId
     * @return PageInfo<Map < String, String>>
     * @throws Exception
     * @Title: getPartyMemberListByPartyOrgId
     * @Description:  按所属党组织获取党员列表
     */
    public PageInfo<Map<String, String>> getPartyMemberListByPartyOrgId(PageParam pageParam, String partyOrgId) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, String>> datalist = getPartyMemberListByPartyOrgId(pageParam.getOrgId(), partyOrgId, pageParam.getSearch());
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(datalist);
        return pageInfo;
    }

    /**
     * @param pageParam
     * @param partyOrgId
     * @return PageInfo<Map < String, String>>
     * @throws Exception
     * @Title: getPartyMemberAccountListByPartyOrgId
     * @Description:  获取账号绑定党员列表
     */
    public PageInfo<Map<String, String>> getPartyMemberAccountListByPartyOrgId(PageParam pageParam, String partyOrgId) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, String>> datalist = getPartyMemberAccountListByPartyOrgId(pageParam.getOrgId(), partyOrgId, pageParam.getSearch());
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(datalist);
        return pageInfo;
    }

    /**
     * @param orgId
     * @param partyOrgId
     * @param year
     * @param search
     * @return List<Map < String, String>>
     * @Title: getPartyVerifyList
     * @Description:  获取考核党员列表
     */
    public List<Map<String, String>> getPartyVerifyList(String orgId, String partyOrgId, String year, String search) {
        return partyMemberMapper.getPartyVerifyList(orgId, partyOrgId, year, "%" + search + "%");
    }

    /**
     * @param pageParam
     * @param partyOrgId
     * @param year
     * @return PageInfo<Map < String, String>>
     * @throws Exception
     * @Title: getPartyVerifyList
     * @Description:  获取考核党员列表
     */
    public PageInfo<Map<String, String>> getPartyVerifyList(PageParam pageParam, String partyOrgId, String year) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, String>> datalist = getPartyVerifyList(pageParam.getOrgId(), partyOrgId, year, pageParam.getSearch());
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(datalist);
        return pageInfo;
    }

    /**
     * @param orgId
     * @param partyOrgId
     * @param beginTime
     * @param endTime
     * @param search
     * @return List<Map < String, String>>
     * @Title: getMemberInFlowList
     * @Description:  获取流入党员列表
     */
    public List<Map<String, String>> getMemberInFlowList(String orgId, String partyOrgId, String beginTime, String endTime, String search) {
        return partyMemberMapper.getMemberInFlowList(orgId, partyOrgId, beginTime, endTime, "%" + search + "%");
    }

    /**
     * @param pageParam
     * @param partyOrgId
     * @param beginTime
     * @param endTime
     * @return PageInfo<Map < String, String>>
     * @throws Exception
     * @Title: getMemberInFlowList
     * @Description:  获取流入党员列表
     */
    public PageInfo<Map<String, String>> getMemberInFlowList(PageParam pageParam, String partyOrgId, String beginTime, String endTime) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, String>> datalist = getMemberInFlowList(pageParam.getOrgId(), partyOrgId, beginTime, endTime, pageParam.getSearch());
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(datalist);
        return pageInfo;
    }

    /**
     * @param orgId
     * @param partyOrgId
     * @return List<Map < String, String>>
     * @Title: getSelectPartyMemberByPartyId
     * @Description:  按党支部获取党员列表
     */
    public List<Map<String, String>> getSelectPartyMemberByPartyId(String orgId, String partyOrgId) {
        return partyMemberMapper.getSelectPartyMemberByPartyId(orgId, partyOrgId);
    }

    /**
     * @param orgId
     * @param searchuser
     * @return List<Map < String, String>>
     * @Title: getPartyMemberBySearchuser
     * @Description:  党员选择时查询
     */
    public List<Map<String, String>> getPartyMemberBySearchuser(String orgId, String searchuser) {
        return partyMemberMapper.getPartyMemberBySearchuser(orgId, "%" + searchuser + "%");
    }

    /**
     * @param orgId
     * @param memberIds
     * @return List<Map < String, String>>
     * @Title: getPartyMemeberByIds
     * @Description:  获取党员姓名列表
     */
    public List<Map<String, String>> getPartyMemeberByIds(String orgId, String memberIds) {
        if (StringUtils.isNotBlank(memberIds)) {
            if (memberIds.equals("@all")) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("memberId", "@all");
                map.put("userName", "全体党员");
                List<Map<String, String>> returnList = new ArrayList<Map<String, String>>();
                returnList.add(map);
                return returnList;
            } else {
                String[] memberArr = memberIds.split(",");
                List<String> list = Arrays.asList(memberArr);
                return partyMemberMapper.getPartyMemeberByIds(orgId, list);
            }
        } else {
            return null;
        }
    }

    /**
     * @param orgId
     * @param memberIds
     * @return RetDataBean
     * @Title: setUnbindAccount
     * @Description:  解除账号
     */
    @Transactional(value = "generalTM")
    public RetDataBean setUnbindAccount(String orgId, String memberIds) {
        try {
            if (StringUtils.isNotBlank(orgId) && StringUtils.isNotBlank(memberIds)) {
                List<String> accountList = new ArrayList<String>();
                String[] memberIdArr = memberIds.split(",");
                List<String> memberIdList = Arrays.asList(memberIdArr);
                List<PartyMember> partyMemberList = getPartyMemberListByList(orgId, memberIdList);
                for (int i = 0; i < partyMemberList.size(); i++) {
                    accountList.add(partyMemberList.get(i).getAccountId());
                }
                if (accountList.size() > 0) {
                    Example example = new Example(Account.class);
                    example.createCriteria().andEqualTo("orgId", orgId).andIn("accountId", accountList);
                    Account account = new Account();
                    account.setMemberId("");
                    accountService.updateAccount(account, example);
                }
                if (memberIdList.size() > 0) {
                    Example example = new Example(PartyMember.class);
                    example.createCriteria().andEqualTo("orgId", orgId).andIn("accountId", accountList);
                    PartyMember partyMember = new PartyMember();
                    partyMember.setAccountId("");
                    updatePartyMember(example, partyMember);
                }
                return RetDataTools.Ok(MessageCode.MESSAGE_SUCCESS);
            } else {
                return RetDataTools.NotOk(MessageCode.MESSAGE_REQUEST_ERROR);
            }
        } catch (Exception e) {
            return RetDataTools.Error(e.getMessage());
        }
    }

    /**
     * @param orgId
     * @param memberIdList
     * @return List<PartyMember>
     * @Title: getPartyMemberListByList
     * @Description:  获取党员列表
     */
    public List<PartyMember> getPartyMemberListByList(String orgId, List<String> memberIdList) {
        Example example = new Example(PartyMember.class);
        example.createCriteria().andEqualTo("orgId", orgId).andIn("memberId", memberIdList);
        return partyMemberMapper.selectByExample(example);
    }


    /**
     * @param orgId
     * @param memberId
     * @param accountId
     * @return RetDataBean
     * @Title: setMemberAccount
     * @Description:  党员信息与系统账号绑定
     */
    @Transactional(value = "generalTM")
    public RetDataBean setMemberAccount(String orgId, String memberId, String accountId) {
        try {
            if (StringUtils.isNotBlank(orgId) && StringUtils.isNotBlank(memberId) && StringUtils.isNotBlank(accountId)) {
                Account account = new Account();
                account.setOrgId(orgId);
                account.setMemberId(memberId);
                int accountCount = accountService.getAccountCount(account);
                if (accountCount > 0) {
                    return RetDataTools.NotOk(MessageCode.MSG_00037);
                }
                PartyMember partyMember = new PartyMember();
                partyMember.setAccountId(accountId);
                int partyMemberCount = getPartyMemberCount(partyMember);
                if (partyMemberCount > 0) {
                    return RetDataTools.NotOk(MessageCode.MSG_00037);
                }
                if (accountCount == 0 && partyMemberCount == 0) {
                    Example example = new Example(Account.class);
                    example.createCriteria().andEqualTo("orgId", orgId).andEqualTo("accountId", accountId);
                    accountService.updateAccount(account, example);
                    Example example2 = new Example(PartyMember.class);
                    example2.createCriteria().andEqualTo("orgId", orgId).andEqualTo("memberId", memberId);
                    updatePartyMember(example2, partyMember);
                }
                return RetDataTools.Ok(MessageCode.MESSAGE_SUCCESS);
            } else {
                return RetDataTools.NotOk(MessageCode.MESSAGE_REQUEST_ERROR);
            }
        } catch (Exception e) {
            return RetDataTools.Error(e.getMessage());
        }

    }

    /**
     * @param partyMember
     * @return int
     * @Title: getPartyMemberCount
     * @Description:  按条件统计党员记录数
     */
    public int getPartyMemberCount(PartyMember partyMember) {
        return partyMemberMapper.selectCount(partyMember);
    }

  /*  @Transactional(value = "generalTM")
    public RetDataBean importPartyMemberByExcel(Account account, MultipartFile file) throws IOException {
        String createTime = SysTools.getTime("yyyy-MM-dd HH:mm:ss");
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        List<String> aList = new ArrayList<String>();
        List<String> uList = new ArrayList<String>();
        Map<String, String> fieldMapA = new HashMap<String, String>();
        fieldMapA.put("姓名", "user_name");
        fieldMapA.put("性别", "sex");
        fieldMapA.put("出生日期", "birthday");
        fieldMapA.put("民族", "nation");
        fieldMapA.put("籍贯", "native_place");
        fieldMapA.put("参加工作时间", "work_ime");
        fieldMapA.put("行政职务", "adm_position");
        fieldMapA.put("所在党支部", "party_org_id");
        fieldMapA.put("身份证号", "card_id");
        fieldMapA.put("学历", "education");
        fieldMapA.put("党籍状态", "party_status");
        List<String> fieldListA = new ArrayList<String>();
        List<String> titleListA = new ArrayList<String>();
        for (Map.Entry<String, String> entry : fieldMapA.entrySet()) {
            fieldListA.add(entry.getValue());
            titleListA.add(entry.getKey());
        }
        String[] fieldArrA = new String[fieldListA.size()];
        fieldListA.toArray(fieldArrA);
        String fieldAString = StringUtils.join(fieldArrA, ",");
        List<Map<String, String>> recordList = ExcelUtil.readExcel(file);
        for (int i = 0; i < recordList.size(); i++) {
            String newAccountId = "";
            Map<String, String> tempMap = recordList.get(i);
            String valueAString = "'" + SysTools.getGUID() + "',";
            for (int k = 0; k < titleListA.size(); k++) {
                if (titleListA.get(k).equals("系统权限")) {
                    UserPriv userPriv = new UserPriv();
                    userPriv.setUserPrivName(tempMap.get(titleListA.get(k)));
                    userPriv.setOrgId(account.getOrgId());
                    userPriv = userPrivService.selectOne(userPriv);
                    if (userPriv != null) {
                        valueAString += "'" + userPriv.getUserPrivId() + "',";
                    } else {
                        return RetDataTools.NotOk("系统权限不存在!--" + tempMap.get(titleListA.get(k)) + "--");
                    }
                } else if (titleListA.get(k).equals("账户")) {
                    newAccountId = tempMap.get(titleListA.get(k));
                    if (StringUtils.isNotBlank(newAccountId)) {
                        int isExistFlag = accountService.isExistAccount(newAccountId);
                        if (isExistFlag == 0) {
                            valueAString += "'" + tempMap.get(titleListA.get(k)) + "',";
                        } else {
                            return RetDataTools.NotOk("账户已存在!--" + tempMap.get(titleListA.get(k)) + "--");
                        }
                    }
                } else {
                    valueAString += "'" + tempMap.get(titleListA.get(k)) + "',";
                }
            }
            String passWord = PasswordEncryptionTools.getEnPassWord(newAccountId);
            valueAString += "'0','" + passWord + "','" + account.getOrgId() + "',0,'" + createTime + "','" + account.getAccountId() + "','" + createTime + "','0','0'";
            String insertSql = "insert into account(account_gu_id," + fieldAString + ",not_login,pass_word,org_id,login_num,update_password_time,create_user,create_time,msg_tip,msg_audio) values" + "(" + valueAString + ")";
            if (StringUtils.isNotBlank(newAccountId)) {
                if (flag) {
                    aList.add(insertSql);
                } else {
                    jdbcTemplate.execute(insertSql);
                }
            }
        }

        List<String> fieldListU = new ArrayList<String>();
        List<String> titleListU = new ArrayList<String>();
        for (Map.Entry<String, String> entry : fieldMapU.entrySet()) {
            fieldListU.add(entry.getValue());
            titleListU.add(entry.getKey());
        }
        String[] fieldArrU = new String[fieldListU.size()];
        fieldListU.toArray(fieldArrU);
        String fieldUString = StringUtils.join(fieldArrU, ",");
        for (int i = 0; i < recordList.size(); i++) {
            String userInfoUserName = "";
            String userInfoAccountId = "";
            Map<String, String> tempMap = recordList.get(i);
            String valueUString = "'" + SysTools.getGUID() + "','" + StrTools.getPinYin(tempMap.get("姓名")) + "',";
            for (int k = 0; k < titleListU.size(); k++) {
                if (titleListU.get(k).equals("部门名称")) {
                    UnitDept unitDept = new UnitDept();
                    unitDept.setDeptName(tempMap.get(titleListU.get(k)));
                    unitDept.setOrgId(account.getOrgId());
                    unitDept = unitDeptService.selectOneUnitDept(unitDept);
                    if (unitDept != null) {
                        valueUString += "'" + unitDept.getDeptId() + "',";
                    } else {
                        return RetDataTools.NotOk("部门不存在!--" + tempMap.get(titleListU.get(k)) + "--");
                    }
                } else if (titleListU.get(k).equals("行政职务")) {
                    UserLevel userLevle = new UserLevel();
                    userLevle.setLevelName(tempMap.get(titleListU.get(k)));
                    userLevle.setOrgId(account.getOrgId());
                    userLevle = userLevelService.selectOne(userLevle);
                    if (userLevle != null) {
                        valueUString += "'" + userLevle.getLevelId() + "',";
                    } else {
                        valueUString += "'',";
                    }
                } else if (titleListU.get(k).equals("姓名")) {
                    userInfoUserName = tempMap.get(titleListU.get(k));
                    valueUString += "'" + userInfoUserName + "',";
                } else if (titleListU.get(k).equals("账户")) {
                    userInfoAccountId = tempMap.get(titleListU.get(k));
                    valueUString += "'" + userInfoAccountId + "',";
                } else {
                    valueUString += "'" + tempMap.get(titleListU.get(k)) + "',";
                }
            }
            valueUString += "'" + account.getOrgId() + "','" + account.getAccountId() + "','" + createTime + "'";
            String insertSql = "insert into user_info(user_info_id,pin_yin," + fieldUString + ",org_id,create_user,create_time) values" + "(" + valueUString + ")";
            if (StringUtils.isNotBlank(userInfoAccountId)) {
                if (flag) {
                    uList.add(insertSql);
                } else {
                    jdbcTemplate.execute(insertSql);
                }
            }
        }
    }*/

}
